/**
 * @ClassDescription:
 * @JdkVersion: 1.8
 * @Author: 李白
 * @Created: 2024/4/21 22:41
 */
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class Main {
    public static void main(String[] args) {
        String inputFile = "input.txt";
        String outputFile = "result.txt";

        // 读取输入文件中的算符优先分析表格数据
        OperatorPrecedenceTable opTable = new OperatorPrecedenceTable(inputFile);

        try (BufferedReader reader = new BufferedReader(new FileReader(inputFile));
             BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {

            String line;
            int step = 0;

            // 读取每一行数据
            while ((line = reader.readLine()) != null) {
                // 这里假设每行是一个待分析的句子
                String inputString = line.trim();

                // 初始化符号栈和输入串
                StringBuilder symbolStack = new StringBuilder("#");
                StringBuilder inputStack = new StringBuilder(inputString);

                // 输出标题
                writer.write("步骤\t符号栈\t\t优先关系\t输入串\t\t移进或归约\n");

                // 开始句子分析
                while (inputStack.length() > 0) {
                    char stackTop = symbolStack.charAt(symbolStack.length() - 1);
                    char inputTop = inputStack.charAt(0);

                    // 获取栈顶字符和输入字符之间的优先关系
                    char precedence = opTable.getPrecedence(stackTop, inputTop);

                    // 输出当前步骤的信息
                    writer.write(String.format("%d\t\t%-10s\t%c\t\t%-10s\t",
                            step, symbolStack.toString(), precedence, inputStack.toString()));

                    // 判断移进或归约
                    if (precedence == '<' || precedence == '=') {
                        // 移进
                        symbolStack.append(inputTop);
                        inputStack.deleteCharAt(0);
                        writer.write("移进\n");
                    } else {
                        // 归约
                        writer.write("归约\n");

                        // 这里可以根据具体的归约规则来修改符号栈
                        // 这里假设归约规则是每次归约一个字符
                        symbolStack.deleteCharAt(symbolStack.length() - 1);
                    }

                    step++;
                }

                // 输出最终结果
                writer.write(String.format("%d\t\t%-10s\t\t\t\t%s\n", step, symbolStack.toString(), "接受"));
                writer.newLine();
                step++;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("句子分析完成，结果已保存到 " + outputFile);
    }
}
